"""
@Author : 合肥一元数智教育科技有限公司
@Date :  2025/6/6 10:58
@Description :  socket server

1. socket服务端对象   ip  port  最大挂起数
2. 监听客户端连接
3. 群发消息
4. 存储所有客户端连接后返回的socket_client
"""
import socket
import threading


class ChatServer:
    # 初始化chat server
    def __init__(self, ip, port, max):
        self.ip = ip
        self.port = port
        self.socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket_server.bind((self.ip, self.port))
        self.socket_server.listen(max)
        self.socket_clients = []

    # 群发消息
    def task(self, socket_client, client_address):
        try:
            while True:
                # 接收客户端发送的数据
                client_message = socket_client.recv(1024).decode('utf-8')
                if client_message:
                    print(f'{client_address}:', client_message)
                    # 发送信息到其它客户端  群发
                    for socket in self.socket_clients:
                        if socket is not socket_client:
                            # 转发信息前 添加ip port前缀 区分信息的发送人
                            socket.send(f'{client_address}:{client_message}'.encode('utf-8'))
                else:
                    break
        except ConnectionResetError as e:
            print(f'{client_address}客户端离线了')
            self.socket_clients.remove(socket_client)
            # 遍历socket  发送客户端离线信息
            for socket in self.socket_clients:
                socket.send(f'{client_address}客户端下线了'.encode('utf-8'))

    # 监听客户端连接
    def start_server(self):
        print('服务端启动等待客户端连接...')
        while True:
            socket_client, address = self.socket_server.accept()
            print(f'{address}客户端连接了')
            thread = threading.Thread(target=self.task, args=(socket_client, address))
            thread.start()
            # 保存客户端socket对象
            self.socket_clients.append(socket_client)


if __name__ == '__main__':
    chat_server = ChatServer('192.168.1.226', 9999, 5)
    # 开启服务器
    chat_server.start_server()
